package com.vincent.filepicker.ability;

import com.vincent.filepicker.Constant;
import com.vincent.filepicker.ResourceTable;
import com.vincent.filepicker.adapter.FolderListAdapter;
import com.vincent.filepicker.adapter.ImagePickAdapter;
import com.vincent.filepicker.adapter.OnSelectStateListener;
import com.vincent.filepicker.filter.FileFilter;
import com.vincent.filepicker.filter.callback.FilterResultCallback;
import com.vincent.filepicker.filter.entity.Directory;
import com.vincent.filepicker.filter.entity.ImageFile;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by Vincent Woo
 * Date: 2016/10/12
 * Time: 16:41
 */

public class ImagePickAbility extends BaseAbility {
    public static final String IS_NEED_CAMERA = "IsNeedCamera";
    public static final String IS_NEED_IMAGE_PAGER = "IsNeedImagePager";
    public static final String IS_TAKEN_AUTO_SELECTED = "IsTakenAutoSelected";

    public static final int DEFAULT_MAX_NUMBER = 9;
    public static final int COLUMN_NUMBER = 3;
    private int mMaxNumber;
    private int mCurrentNumber = 0;
    private ListContainer mRecyclerView;
    private ImagePickAdapter mAdapter;
    private boolean isNeedCamera;
    private boolean isNeedImagePager;
    private boolean isTakenAutoSelected;
    public ArrayList<ImageFile> mSelectedList = new ArrayList<>();
    private List<Directory<ImageFile>> mAll;

    private Text tv_count;
    private Text tv_folder;
    private DirectionalLayout ll_folder;
    private DependentLayout rl_done;
    private DependentLayout tb_pick;
    private final int RESULT_OK = -1;

    @Override
    public void permissionGranted() {
        loadData();
    }

    @Override
    public void permissionDenied() {

    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_vw_ability_image_pick);

        mMaxNumber = getIntent().getIntParam(Constant.MAX_NUMBER, DEFAULT_MAX_NUMBER);
        isNeedCamera = getIntent().getBooleanParam(IS_NEED_CAMERA, false);
        isNeedImagePager = getIntent().getBooleanParam(IS_NEED_IMAGE_PAGER, true);
        isTakenAutoSelected = getIntent().getBooleanParam(IS_TAKEN_AUTO_SELECTED, true);
        initView();
        loadData();
    }

    private void initView() {
        tv_count = (Text) findComponentById(ResourceTable.Id_tv_count);
        tv_count.setText(mCurrentNumber + "/" + mMaxNumber);

        mRecyclerView = (ListContainer) findComponentById(ResourceTable.Id_rv_image_pick);
        TableLayoutManager layoutManager = new TableLayoutManager();
        layoutManager.setColumnCount(COLUMN_NUMBER);
        mRecyclerView.setLayoutManager(layoutManager);
        mAdapter = new ImagePickAdapter(this, isNeedCamera, isNeedImagePager, mMaxNumber);
        mRecyclerView.setItemProvider(mAdapter);

        mAdapter.setOnSelectStateListener(new OnSelectStateListener<ImageFile>() {
            @Override
            public void OnSelectStateChanged(boolean state, ImageFile file) {
                if (state) {
                    mSelectedList.add(file);
                    mCurrentNumber++;
                } else {
                    mSelectedList.remove(file);
                    mCurrentNumber--;
                }
                tv_count.setText(mCurrentNumber + "/" + mMaxNumber);
            }
        });

        rl_done = (DependentLayout) findComponentById(ResourceTable.Id_rl_done);
        rl_done.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component v) {
                Intent intent = new Intent();
                intent.setSequenceableArrayListParam(Constant.RESULT_PICK_IMAGE, mSelectedList);
                setResult(RESULT_OK, intent);
                terminateAbility();
            }
        });

        tb_pick = (DependentLayout) findComponentById(ResourceTable.Id_tb_pick);
        tb_pick.findComponentById(ResourceTable.Id_rl_back).setClickedListener(component -> terminateAbility());
        ll_folder = (DirectionalLayout) findComponentById(ResourceTable.Id_ll_folder);
        if (isNeedFolderList) {
            ll_folder.setVisibility(Component.VISIBLE);
            ll_folder.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component v) {
                    mFolderHelper.toggle(findComponentById(ResourceTable.Id_rv_top_divider));
                }
            });
            tv_folder = (Text) findComponentById(ResourceTable.Id_tv_folder);
            tv_folder.setText(ResourceTable.String_vw_all);

            mFolderHelper.setFolderListListener(new FolderListAdapter.FolderListListener() {
                @Override
                public void onFolderListClick(Directory directory) {
                    mFolderHelper.toggle(tb_pick);
                    tv_folder.setText(directory.getName());

                    if (null == directory.getPath() || directory.getPath().isEmpty()) { //All
                        refreshData(mAll);
                    } else {
                        for (Directory<ImageFile> dir : mAll) {
                            if (dir.getPath().equals(directory.getPath())) {
                                List<Directory<ImageFile>> list = new ArrayList<>();
                                list.add(dir);
                                refreshData(list);
                                break;
                            }
                        }
                    }
                }
            });
        }
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent data) {
        super.onAbilityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Constant.REQUEST_CODE_TAKE_IMAGE:
                if (resultCode == RESULT_OK) {
                    loadData();
                }
                break;
            case Constant.REQUEST_CODE_BROWSER_IMAGE:
                if (resultCode == RESULT_OK) {
                    ArrayList<ImageFile> list = data.getSequenceableArrayListParam(Constant.RESULT_BROWSER_IMAGE);
                    mCurrentNumber = list.size();
                    mAdapter.setCurrentNumber(mCurrentNumber);
                    tv_count.setText(mCurrentNumber + "/" + mMaxNumber);
                    mSelectedList.clear();
                    mSelectedList.addAll(list);

                    for (ImageFile file : mAdapter.getDataSet()) {
                        if (mSelectedList.contains(file)) {
                            file.setSelected(true);
                        } else {
                            file.setSelected(false);
                        }
                    }
                    mAdapter.notifyDataChanged();
                }
                break;
        }
    }

    private void loadData() {
        FileFilter.getImages(this, new FilterResultCallback<ImageFile>() {
            @Override
            public void onResult(List<Directory<ImageFile>> directories) {
                // Refresh folder list
                if (isNeedFolderList) {
                    ArrayList<Directory> list = new ArrayList<>();
                    Directory all = new Directory();
                    all.setName(getString(ResourceTable.String_vw_all));
                    list.add(all);
                    list.addAll(directories);
                    mFolderHelper.fillData(list);
                }

                mAll = directories;
                refreshData(directories);
            }
        });
    }

    private void refreshData(List<Directory<ImageFile>> directories) {
        boolean tryToFindTakenImage = isTakenAutoSelected;

        // if auto-select taken image is enabled, make sure requirements are met
        if (tryToFindTakenImage && null != mAdapter.mImagePath && !mAdapter.mImagePath.isEmpty()) {
            File takenImageFile = new File(mAdapter.mImagePath);
            tryToFindTakenImage = !mAdapter.isUpToMax() && takenImageFile.exists(); // try to select taken image only if max isn't reached and the file exists
        }

        List<ImageFile> list = new ArrayList<>();
        for (Directory<ImageFile> directory : directories) {
            list.addAll(directory.getFiles());

            // auto-select taken images?
            if (tryToFindTakenImage) {
                findAndAddTakenImage(directory.getFiles());   // if taken image was found, we're done
            }
        }

        for (ImageFile file : mSelectedList) {
            int index = list.indexOf(file);
            if (index != -1) {
                list.get(index).setSelected(true);
            }
        }
        Collections.reverse(list);
        mAdapter.refresh(list);
    }

    private boolean findAndAddTakenImage(List<ImageFile> list) {
        for (ImageFile imageFile : list) {
            if (imageFile.getPath().equals(mAdapter.mImagePath)) {
                mSelectedList.add(imageFile);
                mCurrentNumber++;
                mAdapter.setCurrentNumber(mCurrentNumber);
                tv_count.setText(mCurrentNumber + "/" + mMaxNumber);

                return true;   // taken image was found and added
            }
        }
        return false;    // taken image wasn't found
    }

    private void refreshSelectedList(List<ImageFile> list) {
        for (ImageFile file : list) {
            if (file.isSelected() && !mSelectedList.contains(file)) {
                mSelectedList.add(file);
            }
        }
    }

}
